package com.sytc.camera.uicontroller;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import org.zeromq.ZMQ;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * 订阅者和发布者
 */
public class ZeromqController {

    @FXML
    private Label welcomeText;

    @FXML
    private TextArea showMessage;

    private ZMQ.Socket publisherSocket;
    private ZMQ.Socket subscriberSocket;
    private ZMQ.Context context;
    private boolean isReceiving = false;

    @FXML
    public void initialize() {
        // 创建 ZeroMQ 上下文
        context = ZMQ.context(1);

        // 创建 ZeroMQ 发布者套接字 (PUB)
        publisherSocket = context.socket(ZMQ.PUB);
        publisherSocket.bind("tcp://*:5657");  // 发布者端口

        // 创建 ZeroMQ 订阅者套接字 (SUB)
        subscriberSocket = context.socket(ZMQ.SUB);
        subscriberSocket.connect("tcp://localhost:5657");  // 订阅者端口
        subscriberSocket.subscribe("".getBytes());  // 订阅所有消息

        Platform.runLater(() -> {
            // 获取当前场景的窗口
            Stage stage = (Stage) welcomeText.getScene().getWindow();
            // 设置窗口关闭事件处理
            stage.setOnCloseRequest(event -> onClose());
        });
    }

    // 发送消息
    @FXML
    protected void onPushButtonClick() {
        // 创建新的线程来发送消息
        new Thread(() -> {
            String message = "Hello, ZeroMQ!";
            publisherSocket.send(message.getBytes(), 0);
            Platform.runLater(() -> welcomeText.setText("消息发送: " + message));
        }).start();
    }

    // 启动接收线程，开始持续接收消息
    @FXML
    protected void onReceiveButtonClick() {
        if (!isReceiving) {
            isReceiving = true;
            // 启动一个后台线程来持续接收消息
            new Thread(() -> {
                while (isReceiving) {
                    try {
                        byte[] message = subscriberSocket.recv(0);
                        if (message != null) {
                            String msg = new String(message);  // 将接收到的字节数组转为字符串

                            // 获取当前时间戳
                            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());


                            // 在 UI 线程中更新 TextArea
                            Platform.runLater(() -> {
                                // 在 TextArea 中显示消息和时间戳
                                showMessage.appendText("[" + timestamp + "] " + msg + "\n");

                                // 自动滚动到 TextArea 的最后一行
                                showMessage.setScrollTop(Double.MAX_VALUE);
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            // 如果已经在接收消息，提示用户
            Platform.runLater(() -> welcomeText.setText("已经开始接收消息"));
        }
    }

    // 在关闭程序时释放资源
    @FXML
    public void onClose() {
        isReceiving = false;  // 停止接收消息线程
        if (publisherSocket != null) {
            publisherSocket.close();
        }
        if (subscriberSocket != null) {
            subscriberSocket.close();
        }
        if (context != null) {
            context.term();
        }
    }
}
